// pages/goods/search/all.js
const basePage = require('../../../common/BasePage')
const baseList = require('../../../common/BaseList')
Page({
  behaviors: [basePage, baseList],

  /**
   * 页面的初始数据
   */
  data: {
    reqUrl: '/v1/goods',
    reqData: {
      publishState: 2
    },
    latitude: "",
    longitude: "",
    /**购物车数据 */
    cartObj: {},
    loading: false,
    /**购物车总数量 */
    cartNum: 0,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    let globalData = getApp().globalData;
    if (globalData.latitude) {
      this.data.latitude = globalData.latitude;
      this.data.longitude = globalData.longitude
    }
    this.update_cart()
  },
  onShow() {

  },
  search_click(e) {
    console.log('search_click', e);
    // this.data.reqData.goodsName = e.detail.value;
    this.setData({
      "reqData.goodsName": e.detail.value
    })
    this.data.current_page = 0;
    this.req_items();
  },
  update_cart() {
    if (this.data.latitude && this.data.longitude) {
      return this.req_cart()
    }
    wx.getLocation({
      altitude: true,
      highAccuracyExpireTime: 0,
      isHighAccuracy: true,
      type: "gcj02",

      success: (res) => {
        this.data.latitude = getApp().globalData.latitude = res.latitude;
        this.data.longitude = getApp().globalData.longitude = res.longitude;
        this.req_cart()
      },
      fail: (res) => {
        console.log('获取定位失败', res.errMsg);
        if (res.errMsg == 'getLocation:fail auth deny') {
          wx.showModal({

            cancelText: '取消',
            confirmColor: "#11C261",
            confirmText: '去授权',
            content: '请授权定位权限',

            showCancel: true,
            title: '提示',
            success: (result) => {
              if (result.confirm) {
                wx.openSetting({
                  withSubscriptions: true,
                  success: (result) => {
                    wx.navigateBack({
                      delta: 1,

                    })
                  },
                  fail: (res) => {},
                  complete: (res) => {},
                })
              } else {
                wx.navigateBack({
                  delta: 1,

                })
              }
            },

          })
        } else {
          wx.showModal({
            content: '获取定位失败',
            confirmText: "重试",

            showCancel: true,
            title: '提示',
            success: (result) => {
              if (result.confirm) {
                this.update_cart()
              } else {
                wx.navigateBack({
                  delta: 1,

                })
              }

            },
          })
        }

      },
    })


  },
  req_cart() {
    this.request({
      url: this.data.host + "/v1/carts/me",
      data: {
        size: 50,
        latitude: this.data.latitude,
        longitude: this.data.longitude,
      },
    }, res => {

      let obj = {};
      let cartNum = 0;
      res.data.records.map(val => {
        val.goods.map(good => {
          if (!obj[good.goodsSid]) {
            obj[good.goodsSid] = {
              storeSid: good.storeSid,
              number: good.number,
              stock: good.stock,
              cartSid: good.sid
            }
            cartNum += good.number * 1;
          }
        })
      });
      // console.log('购物车1', obj);
      this.setData({
        cartObj: obj,
        cartNum: cartNum
      })
      this.req_items();
    })
  },
  add_cart(e) {
    console.log('add', e.currentTarget.dataset.item);
    let item = e.currentTarget.dataset.item;
    let i = e.currentTarget.dataset.index;
    let that = this;
    if (item.storeSid) {
      return this.req_add_cart(item.storeSid, item, i)
    } else {
      that.request({
        url: that.data.host + '/v1/carts/store/' + item.sid, 
        data: {
          latitude: this.data.latitude,
          longitude: this.data.longitude,
          // goodsSid: that.data.details.sid
        },
        loadingTip: '获取门店'
      }, res => {

        that.req_add_cart(res.data, item, i)
      })
    }

  },
  req_add_cart(storeSid, item, i) {
    this.request({
      url: this.data.host + '/v1/carts/add',
      data: {
        goodsSid: item.sid,
        storeSid: storeSid
      },
      method: 'put',
      loadingTip: '加够...'
    }, res => {

      item.storeSid = storeSid;
      item.number = 1;
      item.cartSid = res.data
      this.data.itemArr[i] = item;
      this.setData({
        itemArr: this.data.itemArr,
        cartNum: this.data.cartNum * 1 + 1
      })
    })
  },
  cart_change(e) {
    console.log("cart_change", e);
    let item = e.currentTarget.dataset.item;
    let i = e.currentTarget.dataset.index;
    if (e.detail.value == 0) {
      //删除购物车
      this.request({
        url: this.data.host + "/v1/carts/del",
        method: "put",
        data: {
          sidList: [item.cartSid]
        }
      }, res => {
        let num = e.detail.value - this.data.itemArr[i].number;
        this.data.itemArr[i].number = e.detail.value;
        this.setData({
          itemArr: this.data.itemArr,
          cartNum: this.data.cartNum + num
        })
      })
    } else {
      //修改购物车数量
      this.request({
        url: this.data.host + "/v1/carts/number",
        method: "put",
        data: {
          number: e.detail.value,
          sid: item.cartSid
        }
      }, res => {
        /**增减数量 */
        let num = e.detail.value - this.data.itemArr[i].number;
        this.data.itemArr[i].number = e.detail.value;
        this.setData({
          itemArr: this.data.itemArr,
          cartNum: this.data.cartNum + num
        })

      })
    }
  },
  /**格式化列表中的数据 */
  init_val(val, index, arr) {
    val.thumb = this.get_imgUrl(val.goodsImg);
    let obj = this.data.cartObj;
    if (obj[val.sid]) {
      let good = obj[val.sid];
      // storeSid: good.storeSid,
      //         number: good.number,
      //         stock: good.stock,
      val.storeSid = good.storeSid;
      val.number = good.number;
      val.stock = good.stock;
      val.cartSid = good.cartSid
    } else {
      val.storeSid = "";
      val.number = 0;
      val.stock = 999;
    }
  },

})